﻿using System.Collections.Generic;
using System.Threading;

namespace Chimp.Core
{
    public class JobSceneManager : ChimpJob
    {
        public List<JobSceneUpdate> Jobs = new List<JobSceneUpdate>();

        public JobSceneManager(ChimpScene s, int threads)
        {
            UpdateDone = false;
            PerformUpdate = true;

            S = s;
            Threads = threads;
            for (int i = 0; i < threads; i++)
            {
                Jobs.Add(new JobSceneUpdate(S, 0, 0));
                Jobs[Jobs.Count - 1].BeginJob();
            }
            BeginJob();
        }

        private ChimpScene S { get; set; }
        private int Threads { get; set; }
        public bool UpdateDone { get; set; }
        public bool PerformUpdate { get; set; }

        public override void PerformJob()
        {
            while (true)
            {
                Lock();

                int oc = S.ObjectList.Count;

                int num = oc/Threads;
                if (num < 128)
                {
                    num = 128;
                }


                int i = 0;
                int dc = 0;
                int jn = 0;
                foreach (JobSceneUpdate j in Jobs)
                {
                    j.Lock();
                    j.Start = i;
                    j.Count = i + num;

                    i += num;
                    jn++;
                    if (PerformUpdate)
                    {
                        j.PerformUpdate = true;
                    }
                    if (j.UpdateDone)
                    {
                        dc++;
                    }
                    j.Release();
                }
                PerformUpdate = false;
                if (dc == Jobs.Count)
                {
                    foreach (JobSceneUpdate j in Jobs)
                    {
                        j.UpdateDone = false;
                    }
                    UpdateDone = true;
                }
                Release();
                Thread.Sleep(8);
            }
        }
    }
}